import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/bloc/LoginCubit.dart';
import 'package:im_app/im/page/view/component/UiUtil.dart';

import '../../../../../demo/DemoPage.dart';
import '../../../../util/ImConstant.dart';
import '../../../InitPatternLockPage.dart';

class PasswordLoginView extends StatefulWidget {
  final String tenantCode;
  final String loginSuccessUrl;

  PasswordLoginView({required this.tenantCode, required this.loginSuccessUrl});

  @override
  State<StatefulWidget> createState() => _PasswordLoginState();
}

class _PasswordLoginState extends State<PasswordLoginView> {
  final _formKey = GlobalKey<FormState>();

  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LoginCubit, LoginState>(listener: (BuildContext context, LoginState loginState) {
      var router = loginState.loginSuccessRouter;
      if (router == 'main') {
        Navigator.of(context).pushNamed(this.widget.loginSuccessUrl);
      } else if (router == 'slide') {
        Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
          return InitPatternLockPage(
            tenantCode: this.widget.tenantCode,
            loginSuccessUrl: this.widget.loginSuccessUrl,
            titleName: '设置滑屏密码',
          );
        }));
      }
    }, builder: (BuildContext context, LoginState state) {
      return Form(
        key: _formKey,
        child: ListView(
          children: <Widget>[
            const SizedBox(height: 10.0),
            _buildUserIdTextField(),
            const SizedBox(height: 30.0),
            _buildPasswordTextField(context),
            const SizedBox(height: 30.0),
            _buildLoginingPane(context),
            const SizedBox(height: 30.0),
            _buildLoginButton(context),
          ],
        ),
      );
    }, );
  }

  Widget _buildUserIdTextField() {
    final loginCubit = context.watch<LoginCubit>();
    if (loginCubit.state.name != '') {
      _controller.text = loginCubit.state.name;
    }
    return TextFormField(
      controller: _controller,
      decoration: InputDecoration(
        hintText: "请输入登录号",
        border: OutlineInputBorder(borderSide: BorderSide(color: ImConstant.IM_LOGIN_DEFAULT_COLOR)),
        iconColor: ImConstant.IM_LOGIN_DEFAULT_COLOR,
        prefixIcon: IconButton(
          disabledColor: ImConstant.IM_LOGIN_DEFAULT_COLOR,
          icon: const Icon(Icons.account_circle_rounded),
          onPressed: null,
          color: ImConstant.IM_LOGIN_DEFAULT_COLOR,
        ),
        suffixIcon: loginCubit.state.name != ''
            ? IconButton(
                color: ImConstant.IM_LOGIN_DEFAULT_COLOR,
                icon: const Icon(Icons.highlight_remove_sharp),
                onPressed: () {
                  _controller.clear();
                  loginCubit.add(new LoginUserChange(''));
                },
              )
            : null,
      ),
      validator: (v) {
        if (v == "") return "请输入登录号";
        return null;
      },
      onChanged: (value) {
        loginCubit.add(LoginUserChange(value));
      },
    );
  }

  Widget _buildPasswordTextField(BuildContext context) {
    final loginCubit = context.watch<LoginCubit>();
    return TextFormField(
      obscureText: loginCubit.state.isCanSeePassword,
      onChanged: (v) {
        loginCubit.add(new LoginPasswordChange(v.toString()));
      },
      validator: (v) {
        if (v == "") return "请输入密码";
        return null;
      },
      decoration: InputDecoration(
          hintText: "请输入密码",
          border: OutlineInputBorder(borderSide: BorderSide(color: ImConstant.IM_LOGIN_DEFAULT_COLOR)),
          prefixIcon: IconButton(
            disabledColor: ImConstant.IM_LOGIN_DEFAULT_COLOR,
            icon: const Icon(Icons.key_sharp),
            onPressed: null,
            color: ImConstant.IM_LOGIN_DEFAULT_COLOR,
          ),
          suffixIcon: IconButton(
            color: ImConstant.IM_LOGIN_DEFAULT_COLOR,
            icon: loginCubit.state.isCanSeePassword ? _buildSvg('assets/svg/eye-open.svg') : _buildSvg('assets/svg/eye-closed.svg'),
            onPressed: () {
              setState(() {
                 loginCubit.add(new LoginSeePassword(!loginCubit.state.isCanSeePassword));
              });
            },
          )),
    );
  }

  Widget _buildLoginingPane(BuildContext context) {
    final loginCubit = context.watch<LoginCubit>();
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Visibility(
          visible: loginCubit.state.isLogining,
          replacement: const SizedBox(height: 30,),
          child: const SizedBox(
            width: 30,
            height: 30,
            child: CupertinoActivityIndicator(),
          ),
        ),
        SizedBox(
          width: 150,
          child: Row(
            children: [
              Visibility(
                visible: loginCubit.state.isError,
                replacement: const SizedBox(height: 30,),
                child: buildSvgView('assets/svg/error.svg', 30, 30, Colors.red),
              ),
              const SizedBox(width: 10,),
              Text(loginCubit.state.msg, style: TextStyle(color: loginCubit.state.isError ? Colors.red : ImConstant.IM_LOGIN_DEFAULT_COLOR,
                  fontWeight: FontWeight.w500))
            ],
          ),
        )
      ],

    );
  }

  Row _buildLoginButton(BuildContext context) {
    final loginCubit = context.watch<LoginCubit>();
    final ButtonStyle style =
        ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20), backgroundColor: Colors.lightBlue);

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          height: 45.0,
          width: 230.0,
          child: ElevatedButton(
            onPressed: loginCubit.state.isLogining ? null : () => _loginAct(context),
            style: style, child: const Text('登录'), ),
        ),
        GestureDetector(
          onTap: ()=>{
            Navigator.of(context).push(MaterialPageRoute(builder: (context)=> DemoPage()))
          },
          child: const Padding(padding: EdgeInsets.only(left: 10), child: Text('?'),),
        )
      ],
    );
  }

  Widget _buildSvg(String assetFile) {
    return buildSvgView(assetFile, 20, 20, ImConstant.IM_LOGIN_DEFAULT_COLOR);
  }

  Future<void> _loginAct(BuildContext context) async {
    LoginCubit loginCubit = context.read<LoginCubit>();
    if (_formKey.currentState!.validate()) {
      if (loginCubit.state.isLogining) return;
      loginCubit.add(new LoginSubmit(loginCubit.state.name, loginCubit.state.password, this.widget.tenantCode));
      _formKey.currentState?.save();
      if (true)return;
    }
  }
}
